/**
 * @filename:BomServiceImpl Dec 11, 2023
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.Bom;
import com.wonder.app.domain.Bomlist;
import com.wonder.app.domain.StockList;
import com.wonder.app.domain.Synbd;
import com.wonder.app.mapper.BomDao;
import com.wonder.app.mapper.BomlistDao;
import com.wonder.app.mapper.SynbdDao;
import com.wonder.app.service.BomService;
import com.wonder.app.request.BomRequest;
import com.wonder.app.service.BomlistService;
import com.wonder.app.service.KingdeeBasicService;
import com.wonder.app.service.SynbdService;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.ConvertDate;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.common.AjaxResult;

import java.util.*;

import com.wonder.common.utils.Threads;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**   
 * @Description:TODO(Bom管理服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class BomServiceImpl  extends ServiceImpl<BomDao, Bom> implements BomService  {
	private static final Logger logger = LoggerFactory.getLogger(BomServiceImpl.class);
    /**
     * 验证Bom管理信息
     * 
     * @param bom
     * @param type
     * @return String
     */
	@Autowired
	private IVtuzxKingdeeService kingdeeService;
	@Autowired
	private ConvertDate convertDate;
	@Autowired
	private BomDao bomDao;
	@Autowired
	private BomlistDao bomlistDao;
	@Autowired
	private  BomService bomService;
	@Autowired
	private BomlistService bomlistService;
	@Autowired
	private SynbdDao synbdDao;
	@Autowired
	private SynbdService synbdService;

	@Autowired
	private KingdeeBasicService kingdeeBasicService;

    @Override
    public String validate(Bom bom,String type){
    
    
       return "";
    }
    
    
    /**
	 * Description:Bom管理分页返回
	 * @param request //检索条件
	 * @param page //分页参数
	 * @return IPage<Bom>   //分页记录
	 */
	@Override 
	public IPage<Bom> selectList(BomRequest request, Page<Bom> page){
	    LambdaQueryWrapper<Bom> lambdaQueryWrapper = new LambdaQueryWrapper<>();
	    
	    if (null != request.getId()) {
	       lambdaQueryWrapper.eq(Bom::getId, request.getId());
	      }               
             
        if (StringUtils.hasText(request.getFNUMBER())) {
			    lambdaQueryWrapper.like(Bom::getFNUMBER, request.getFNUMBER()); 
		    } 
             
        if (StringUtils.hasText(request.getFDOCUMENTSTATUS())) {
			    lambdaQueryWrapper.eq(Bom::getFDOCUMENTSTATUS, request.getFDOCUMENTSTATUS());
		    } 
             
        if (StringUtils.hasText(request.getFGROUP())) {
			    lambdaQueryWrapper.eq(Bom::getFGROUP, request.getFGROUP());
		    } 
             
        if (StringUtils.hasText(request.getFMATERIALNO())) {
			    lambdaQueryWrapper.like(Bom::getFMATERIALNO, request.getFMATERIALNO()); 
		    } 
             
        if (StringUtils.hasText(request.getFMATERIALNAME())) {
			    lambdaQueryWrapper.like(Bom::getFMATERIALNAME, request.getFMATERIALNAME()); 
		    } 
             
        if (StringUtils.hasText(request.getFSPECIFICATION())) {
			    lambdaQueryWrapper.like(Bom::getFSPECIFICATION, request.getFSPECIFICATION()); 
		    } 
             
        if (StringUtils.hasText(request.getFCREATEORGNAME())) {
			    lambdaQueryWrapper.like(Bom::getFCREATEORGNAME, request.getFCREATEORGNAME()); 
		    } 
             
        
		lambdaQueryWrapper.orderByDesc(Bom::getId);	
		Page<Bom> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
		return selectPage;
    }

	/**
	 * 同步BOM
	 * @throws Exception
	 */
	public void syncBom (String endTime) throws Exception{
		syncBom(1,50,endTime);
	}
	private void  syncBom(int start , int limit,String endTime)throws Exception {

		String cond = String.format("FCreateDate > '%s' or FModifyDate > '%s'", endTime, endTime);

		VtuzxKingdeeCloudClient clent = kingdeeService.loginKingdee();
		ArrayList<String> arrayList = new ArrayList<>();
		arrayList.add("FID");//主键
		arrayList.add("FNUMBER");//BOM编号
		arrayList.add("FBILLTYPE");//单据类型
		arrayList.add("FDOCUMENTSTATUS");//数据状态
//		arrayList.add("FBOMUSE");//BOM用途
		arrayList.add("FGROUP.fnumber");//BOM分组
		arrayList.add("FBOMCATEGORY");//BOM大类
		arrayList.add("FMATERIALID.fnumber");//父项物料编码
		arrayList.add("FITEMNAME");//父项物料名称
		arrayList.add("FITEMMODEL");//父项物料规格
		arrayList.add("FUNITID.fname");//单位
		arrayList.add("FCREATEORGID");//创建组织内码
		arrayList.add("FCREATEORGID.fname");//创建组织名称
		arrayList.add("FUSEORGID");//使用组织内码
		arrayList.add("FUSEORGID.fname");//使用组织名称
		arrayList.add("FCREATEDATE");//创建日期
		arrayList.add("FMODIFYDATE");//修改日期
		arrayList.add("FTreeEntity_FENTRYID");//分录内码
		arrayList.add("FMATERIALIDCHILD");//子项物料编码
		arrayList.add("FCHILDITEMNAME");//子项物料名称
		arrayList.add("FCHILDITEMMODEL");//子项物料规格
		arrayList.add("FChildBaseUnitID.fname");//子项物料单位
		arrayList.add("FNUMERATOR");//分子
		arrayList.add("FDENOMINATOR");//分母
		arrayList.add("FFIXSCRAPQTY");//固定损耗率
		arrayList.add("FSCRAPRATE");//变动损耗率
		arrayList.add("FOWNERID");//货主

		List<VtuzxMap> bomQuery = kingdeeService.query(clent, "ENG_BOM", arrayList,
				cond, "FID", 0, 50);
		Set<Bom> bomSetinsert = new HashSet<>();//父项新增
		Set<Bom> bomsetupdate = new HashSet<>();//父项修改
		List<Bom> bominsert = new ArrayList<>();//父项新增
		List<Bom> bomupdate = new ArrayList<>();//父项修改
		List<Bomlist> bomlistinsert = new ArrayList<>();//子项新增
		List<Bomlist> bomlistupdate = new ArrayList<>();//子项修改
		for (VtuzxMap Bom : bomQuery) {
			Bom bom = new Bom();
			Bomlist bomlist1 = new Bomlist();
			Long FID = Bom.getLong("FID");
			bom.setFID(FID);
			bom.setFNUMBER(Bom.getString("FNUMBER"));//编码
			bom.setFBILLTYPE(Bom.getString("FBILLTYPE"));//类型
			bom.setFDOCUMENTSTATUS(Bom.getString("FDOCUMENTSTATUS"));//数据状态
//			bom.setFBOMUSE(Bom.getString("FBOMUSE"));//BOM用途
			bom.setFGROUP(Bom.getString("FGROUP.fnumber"));//BOM分组
			bom.setFBOMCATEGORY(Bom.getString("FBOMCATEGORY"));//BOM大类
			bom.setFMATERIALNO(Bom.getString("FMATERIALID.fnumber"));//父项物料编码
			bom.setFMATERIALNAME(Bom.getString("FITEMNAME"));//父项物料名称
			bom.setFSPECIFICATION(Bom.getString("FITEMMODEL"));//父项物料规格
			bom.setFUNITID(Bom.getString("FUNITID.fname"));//父项物料单位
			bom.setFCREATEORGID(Bom.getLong("FCREATEORGID"));//创建组织内码
			bom.setFCREATEORGNAME(Bom.getString("FCREATEORGID.fname"));//创建组织名称
			bom.setFUSEORGID(Bom.getLong("FUSEORGID"));//使用组织内码
			bom.setFUSEORGIDNAME(Bom.getString("FUSEORGID.fname"));//使用组织名称
			String FCreateDate = Bom.getObject("FCREATEDATE");//创建时间
			Date ConverFCREATEDATE = ConvertDate.convertToDatabaseDateTime(FCreateDate, "yyyy-MM-dd'T'HH:mm:ss.SSS");
			bom.setFCREATEDATE(ConverFCREATEDATE);//创建日期
			String FMODIFYDATE = Bom.getObject("FMODIFYDATE");
			Date ConverFMODIFYDATE =null;
			if(FMODIFYDATE != null) {
				ConverFMODIFYDATE = ConvertDate.convertToDatabaseDateTime(FMODIFYDATE, "yyyy-MM-dd'T'HH:mm:ss.SSS");
			}
			bom.setFMODIFYDATE(ConverFMODIFYDATE);//修改日期
			bomlist1.setDetailid(Bom.getLong("FID"));//表体Detailid
			Long FENTRYID = Bom.getLong("FTreeEntity_FENTRYID");//分录内码
			bomlist1.setFENTRYID(FENTRYID);//分录内码
			bomlist1.setFMATERIALNO(Bom.getString("FMATERIALIDCHILD"));//子项物料编码
			bomlist1.setFMATERIALNAME(Bom.getString("FCHILDITEMNAME"));//子项物料名称
			bomlist1.setFSPECIFICATION(Bom.getString("FCHILDITEMMODEL"));//子项物料规格
			bomlist1.setFUNITID(Bom.getString("FChildBaseUnitID.fname"));//子项物料单位
			bomlist1.setFNUMERATOR(Bom.getDouble("FNUMERATOR"));//分子
			bomlist1.setFDENOMINATOR(Bom.getDouble("FDENOMINATOR"));//分母
			bomlist1.setFFIXSCRAPQTY(Bom.getDouble("FFIXSCRAPQTY"));//固定损耗率
			bomlist1.setFSCRAPRATE(Bom.getDouble("FSCRAPRATE"));//变动损耗率
			bomlist1.setFOWNERID(Bom.getLong("FOWNERID"));//货主
			String Convertime = VtuzxUtil.formatYmdHmsF(ConverFMODIFYDATE);
			QueryWrapper<Bom> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("id", FID);
			List<Bom> selectBom = bomDao.selectList(queryWrapper);//判断数据库BOM表头是否存在
			QueryWrapper<Bomlist> queryWrapperbomlist = new QueryWrapper<>();
			queryWrapperbomlist.eq("FENTRYID",FENTRYID);
			List<Bomlist> selectBomlist =bomlistDao.selectList(queryWrapperbomlist);//判断表体是否存在
			Long bomid = null;
			Long bomlistid = null;
			boolean exists = bominsert.contains("fid");
			for (Bom Bomid :selectBom) {
				bomid = Bomid.getId();
			}
			for (Bomlist Bomlistid : selectBomlist){
				bomlistid =Bomlistid.getId();
			}
			if (bomid != null) {
				bom.setId(bomid);
			}
			if (bomlistid != null){
				bomlist1.setId(bomlistid);
			}
//			if(selectBom.size() == 0){
//				bominsert.add(bom);
//			}
			if(selectBom.size() == 0){
				bomSetinsert.add(bom);
			}
			if (selectBomlist.size() == 0){
				bomlistinsert.add(bomlist1);
			}
			//判断修改日期是否大于最后同步时间
			int result = 0;
			if (endTime != null) {
				result = Convertime.compareTo(endTime);
			}
			//需要修改 已经存在并且修改日期大于最后同步日期
//			if(selectBom.size() > 0 && result >0) {
//				bomupdate.add(bom);
//			}
			if(selectBom.size() > 0 && result >0) {
				bomsetupdate.add(bom);
			}
			if (selectBomlist.size()>0 && result >0){
				bomlistupdate.add(bomlist1);
			}
		}
		//新增BOM
//		if(!bominsert.isEmpty()){
//			bomService.saveBatch(bominsert);
//		}
		if(!bomSetinsert.isEmpty()){
			bomService.saveBatch(bomSetinsert);
		}
		//修改BOM
		if(!bomsetupdate.isEmpty()){
			bomService.updateBatchById(bomsetupdate);
		}
		if (!bomlistinsert.isEmpty()){
			bomlistService.saveBatch(bomlistinsert);
		}
		if (!bomlistupdate.isEmpty()){
			bomlistService.updateBatchById(bomlistupdate);
		}
		if (bomQuery.size() >= limit) {
			syncBom(start + limit, limit,endTime);
		}
	}
	}
        
    
